package lab.user.action;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;

import lab.user.pojo.User;
import lab.user.service.impl.UserServiceImpl;


public class UserLoginAction extends ActionSupport implements ServletResponseAware, ServletRequestAware {
	
	private static final long serialVersionUID = 1L;
	private String password;
	private String username = null;
	
	protected HttpServletResponse servletResponse;  
	@Override   
	public void setServletResponse(HttpServletResponse servletResponse) {   
		this.servletResponse = servletResponse;   
	}   
	
	protected HttpServletRequest servletRequest;   
	@Override   
	public void setServletRequest(HttpServletRequest servletRequest) {   
		this.servletRequest = servletRequest;   
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	} 
	
	public String execute() {
		User user = new User();
		user.setUserName(this.username);
		user.setPassword(this.password);
		UserServiceImpl service = new UserServiceImpl();
		if (service.login(user)) {
			//set cookie
			Cookie cookie = new Cookie("LabUser", username);  
			cookie.setMaxAge(60*60*24*365); // Make the cookie last a year  
			servletResponse.addCookie(cookie); 
			return "success";
		}
		else {
			addFieldError("username","Invalid username or password");
			return "input";
		}
	}

}
